﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;

namespace Technoera.Common.Interop.OleDb
{
    public sealed class XlsReader : IDisposable
    {
        public XlsReader(string xlsFullFileName, ExcelVersion excelVersion)
        {
            if (!System.IO.File.Exists(xlsFullFileName)) throw new System.IO.FileNotFoundException(xlsFullFileName);
            cn = new OleDbConnection(XlsHelper.GetExcelConnectionString(xlsFullFileName, excelVersion));
            cmd = new OleDbCommand();
            cmd.Connection = cn;
        }

        ~XlsReader()
        {
            if (!wasDisposed) Dispose();
            GC.SuppressFinalize(this);
        }

        private bool wasDisposed = false;
        private OleDbConnection cn;
        private OleDbCommand cmd;

        public OleDbDataReader GetDataReader(string sheetName)
        {
            cmd.CommandText = String.Format("SELECT * FROM [{0}$]", sheetName);
            cn.Open();
            return cmd.ExecuteReader();
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (cmd != null) cmd.Dispose();
            if (cn != null)
            {
                if (cn.State == System.Data.ConnectionState.Open) cn.Close();
                cn.Dispose();
            }
            wasDisposed = true;
        }

        #endregion
    }
}
